﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.EnterpriseServices.Internal;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using System.Xml.Linq;
using YunShop_WebAPI.BLL;
using YunShop_WebAPI.BLL.SxfPay;
using YunShop_WebAPI.Model;

namespace YunShop_WebAPI.API.Controllers
{
    public class MemberCardController : ApiController
    {


        /// <summary>
        /// 通过code换取openId和session_key
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [ActionName("OnLogin")]
        public Result_Model OnLogin()
        {
            string msg = "登录异常!";
            int status = 0;

            string appid = CommonFun.ConvertToString(HttpContext.Current.Request["appid"]);
            string code = CommonFun.ConvertToString(HttpContext.Current.Request["code"]);
            string scene = CommonFun.ConvertToString(HttpContext.Current.Request["scene"]);
            object dt = MemberCardService.OnLogin(appid, code, scene, ref msg, ref status);
            return new Result_Model(status, msg, dt);
        }

        /// <summary>
        /// 获取会员信息 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [ActionName("GetMemberData")]
        public Result_Model GetMemberData()
        {
            var msg = "";
            var status = 0;
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            List<MemberDataResponse> data = MemberCardService.GetMemberData(sSystemAppID);
            if (data == null || data.Count == 0)
            {
                status = 0;
                msg = "会员信息不存在，请创建";
            }
            else
            {
                status = 1;
                //MemberId = data[0].MemberId.ToString();
            }
            return new Result_Model(status, msg, data);
        }



        [HttpPost]
        [HttpGet]
        [ActionName("SystemParam")]
        public Result_Model SystemParam()
        {
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            string corpid = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID).ToString();
            string hostid = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.HostID).ToString();
            string msg = "";
            Hashtable result = new Hashtable();
            var bOk = false;
            Hashtable data = new Hashtable();
            if (string.IsNullOrEmpty(corpid))
            {
                msg = "分店定位信息错误";
            }
            else
            {
                data = MemberCardService.SystemParam(hostid, corpid);
                if (data != null)
                {
                    data["corpid"] = corpid;
                    data["hostid"] = hostid;
                    result = data;
                    bOk = true;
                }
            }
            return new Result_Model(bOk ? 1 : 0, msg, result);
        }

        /// <summary>
        /// 获取礼券列表接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionName("CouponList")]
        public Result_Model CouponList()
        {
            int status = 0;
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            int corpId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);
            int memberId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);
            int type = CommonFun.ConvertToInt(HttpContext.Current.Request["type"]);
            ArrayList dt = MallService.GetCouponList(corpId, memberId, type);
            status = 1;
            return new Result_Model(status, "获取成功！", dt);
        }


        [HttpPost, HttpGet]
        [ActionName("GetCouponById")]
        public async Task<Result_Model> GetCouponById()
        {
            int status = 0;
            long m_MemberId = CommonFun.ConvertToBigInt(HttpContext.Current.Request["MemberId"]);
            long id = CommonFun.ConvertToBigInt(HttpContext.Current.Request["id"]);
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            int corpId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);
            int memberId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);
            ArrayList dt = MallService.GetCouponById(corpId, m_MemberId, id);
            status = 1;
            return new Result_Model(status, "获取成功！", dt?[0]);
        }


        /// <summary>
        /// 充值赠送金额接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionName("DepositGiveData")]
        public Result_Model DepositGiveData()
        {
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            int corpId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);
            int memberId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);
            List<t_MemberDepositGive> result = MemberCardService.DepositGiveData(corpId, memberId, sSystemAppID);
            return new Result_Model(1, "获取成功!", result);
        }


        /// <summary>
        /// 分页获取会员卡消费记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionName("GetMemberDeposit")]
        public Result_Model GetMemberDeposit()
        {
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            Int64 memberId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);
            int pageIndex = CommonFun.ConvertToInt(HttpContext.Current.Request["PageIndex"]) - 1;
            int pageSize = CommonFun.ConvertToInt(HttpContext.Current.Request["PageSize"]);
            int mDataType = CommonFun.ConvertToInt(HttpContext.Current.Request["DataType"]);
            string mDateStar = CommonFun.ConvertToString(HttpContext.Current.Request["DateStar"]);
            string mDateEnd = CommonFun.ConvertToString(HttpContext.Current.Request["DateEnd"]);
            if (string.IsNullOrEmpty(mDateStar)) mDateStar = System.DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd");
            if (string.IsNullOrEmpty(mDateEnd)) mDateEnd = System.DateTime.Now.ToString("yyyy-MM-dd");
            string sHostId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID).ToString();
            List<MemberDepositResponse> result = MemberCardService.GetMemberDeposit(memberId, mDataType, mDateStar, mDateEnd, pageIndex, pageSize, sSystemAppID);
            return new Result_Model(1, "获取成功!", result);

        }


        /// <summary>
        /// 次卡方案
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionName("GetMemberTime")]
        public Result_Model GetMemberTime()
        {
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);

            int CorpID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);
            int stockID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.StockID);

            List<MemberTimeResponse> result = MemberCardService.GetMemberTime(stockID, CorpID, sSystemAppID);
            return new Result_Model(1, "获取成功!", result);

        }


        /// <summary>
        /// 分页获取会员积分记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionName("GetMemberPoint")]
        public Result_Model GetMemberPoint()
        {
            var pageIndex = HttpContext.Current.Request["PageIndex"];
            var pageSize = HttpContext.Current.Request["PageSize"];
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);

            string MemberId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID).ToString();
            string HostId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.HostID).ToString();
            string memberId = MemberId;//GetSession("MemberId");

            if (string.IsNullOrEmpty(memberId))
            {
                memberId = HttpContext.Current.Request["MemberId"];
            }
            var result = MemberCardService.GetMemberPoint(HostId, memberId, pageIndex, pageSize, sSystemAppID);
            return new Result_Model(1, "获取成功!", result);
        }


        /// <summary>
        /// 修改会员昵称、性别、生日
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("EditDetail")]
        public Result_Model EditDetail()
        {
            string Name = (HttpContext.Current.Request["Name"]);
            int sex = CommonFun.ConvertToInt(HttpContext.Current.Request["Sex"]);
            string Birthday = (HttpContext.Current.Request["Birthday"]);
            string Email = (HttpContext.Current.Request["Email"]);
            string Address = (HttpContext.Current.Request["Address"]);
            string phone = (HttpContext.Current.Request["phone"]);

            string msg;
            var status = 0;
            dynamic data = null;
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);

            try
            {
                int CorpID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);
                Int64 memberId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);

                if (CorpID <= 0)
                {
                    msg = "门店定位错误";
                }
                else if (memberId <= 0)
                {
                    msg = "未绑定会员";
                }
                else
                {
                    if (MemberCardService.UpdateMemberData(memberId, phone, CorpID, Name, sex, Birthday, Email, Address))
                    {
                        status = 1;
                        msg = "修改成功";
                        //data = MiniProgramService.GetMemberData(HostId, phone, corpId);
                        data = MemberCardService.GetMemberDataByID(memberId, CorpID, sSystemAppID);
                    }
                    else
                    {
                        status = 0;
                        msg = "修改失败";
                    }
                }
            }
            catch
            {
                return new Result_Model(0, "修改失败");
            }
            return new Result_Model(status, msg, data);

        }


        /// <summary>
        /// 获取次卡列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionName("MemberTimeList")]

        public Result_Model MemberTimeList()
        {
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            Int64 memberId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);
            int CorpID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);
            int stockID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.StockID);
            if (stockID <= 0)
            {
                return new Result_Model(0, "未定位门店");
            }
            //var data = MemberService.GetMemberTimeByMemberId(stockId, memberId);
            List<MemberTimeResponse> data = MemberCardService.MemberTimeList(CorpID, stockID, memberId);
            return new Result_Model(1, "获取成功!", data);

        }


        [HttpPost]
        [ActionName("MemberTimeDtl")]

        public Result_Model MemberTimeDtl()
        {
            long id = CommonFun.ConvertToBigInt(HttpContext.Current.Request["id"]);

            if (id <= 0)
            {
                return new Result_Model(0, "请输入次卡Id");
            }
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            List<MemberTimeStockResponse> data = MemberCardService.GetMemberTimeStock(id);
            return new Result_Model(1, "获取成功!", data);
        }

        [HttpGet]
        [HttpPost]
        [ActionName("GetGoodsList")]
        public Result_Model GetGoodsList()
        {
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            int mCorpID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);
            int mPageIndex = CommonFun.ConvertToInt(HttpContext.Current.Request["page_index"]) - 1;
            int mPageSize = CommonFun.ConvertToInt(HttpContext.Current.Request["page_size"]);
            int mClassID = CommonFun.ConvertToInt(HttpContext.Current.Request["class_id"]);
            int mBrandID = CommonFun.ConvertToInt(HttpContext.Current.Request["brand_id"]);
            int mOrderType = CommonFun.ConvertToInt(HttpContext.Current.Request["order_type"]);
            string mConditon = CommonFun.ConvertToString(HttpContext.Current.Request["condition"]);
            int status = 0;

            string message = "获取成功";
            status = 1;
            //pr_wap_GetGoodFormClass
            ArrayList jsonData = MallService.GetGoodsList(mCorpID, mPageIndex, mPageSize, mClassID, mBrandID, mConditon, mOrderType);
            int count = MemberCardService.GetGoodsListCount(mCorpID, mClassID, mBrandID, mConditon, mOrderType); ;
            return new Result_Model(status, message, jsonData, count);
        }


        /// <summary>
        /// 1.15、商品详情
        /// </summary>
        [HttpPost, HttpGet]
        [ActionName("GetGoodsDetails")]
        public Result_Model GetGoodsDetails()
        {
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            Int64 goods_id = CommonFun.ConvertToBigInt(HttpContext.Current.Request["goods_id"]);
            Hashtable data = MemberCardService.GetGoodsDetail(sSystemAppID, goods_id);
            return new Result_Model(1, "获取成功", data);
        }


        [HttpPost, HttpGet]
        [ActionName("GetAddressList")]
        public async Task<Result_Model> GetAddressList()
        {
            int status = 0;
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            long m_WeixinID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.WeixinID); // 3
            if (m_WeixinID > 0)
            {
                StringBuilder strSql = new StringBuilder();
                List<SqlParameter> ltpara = new List<SqlParameter>();
                strSql.Append(@"select *  from t_WxUserAddress     where FWeixinID= @FWeixinID   ");
                ltpara.Add(new SqlParameter("@FWeixinID", m_WeixinID));
                ArrayList dt = DBHelper.Select(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
                status = 1;
                return new Result_Model(status, "获取成功！", dt);
            }
            return new Result_Model(status, "WeixinID 为空,请重新登录");

        }

        /// <summary>
        /// 手机号一键登录
        /// </summary>
        [HttpPost, HttpGet]
        [ActionName("LoginByPhoneOneKey")]
        public async Task<Result_Model> LoginByPhoneOneKey()
        {
            string shop_appid = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["shop_appid"]);
            long m_CorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID); // 1
            long m_PtCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.TopCorpID); // 3
            long m_StockID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.StockID); // 3
            string m_code = CommonFun.ConvertToString(HttpContext.Current.Request["code"]);
            string m_openId = CommonFun.ConvertToString(HttpContext.Current.Request["openId"]);
            string m_appId = CommonFun.ConvertToString(HttpContext.Current.Request["appId"]);
            int CorpId = CommonFun.ConvertToInt(HttpContext.Current.Request["CorpId"]);
            if (m_CorpID == 0)
            {
                m_CorpID = CorpId;
            }

            long FStockID = CommonFun.ConvertToBigInt(HttpContext.Current.Request["FStockID"]);
            if (m_StockID == 0)
            {
                m_StockID = FStockID;
            }
            int FParentID = CommonFun.ConvertToInt(HttpContext.Current.Request["FParentID"]);
            return await MallService.LoginByPhoneOneKey((int)m_CorpID, m_code, m_openId, m_StockID, m_appId, FParentID);
        }


        [HttpPost, HttpGet]
        [ActionName("SetDefaultAddress")]
        public Result_Model SetDefaultAddress()
        {
            int status = 0;
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            long id = CommonFun.ConvertToBigInt(HttpContext.Current.Request["id"]);
            long m_WeixinID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.WeixinID); // 3
            if (m_WeixinID == 0 || id == 0)
            {
                return new Result_Model(status, "设置失败,id为空或用户为登录!");

            }

            bool res = MallService.SetDefaultAddress(id, m_WeixinID);
            return new Result_Model(res ? 1 : 0, res ? "设置成功！" : "设置失败!", res);
        }



        [HttpPost, HttpGet]
        [ActionName("SaveAddress")]
        public Result_Model SaveAddress()
        {
            int status = 0;
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            string json = CommonFun.ConvertToString(HttpContext.Current.Request["json"]);
            long m_WeixinID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.WeixinID); // 3

            bool res = MallService.SaveAddress(json, m_WeixinID);
            status = 1;

            return new Result_Model(status, "编辑成功！", res);
        }



        /// <summary>
        /// 兑换商品
        /// </summary>
        /// <returns></returns>
        [HttpPost, HttpGet]
        [ActionName("ExchangeGood")]
        public Result_Model ExchangeGood()
        {
            int status = 0;
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            string json = CommonFun.ConvertToString(HttpContext.Current.Request["json"]);
            long m_WeixinID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.WeixinID); // 3

            bool res = MallService.SaveAddress(json, m_WeixinID);
            status = 1;

            return new Result_Model(status, "编辑成功！", res);
        }

        #region 提交订单
        /// <summary>
        /// 提交订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, HttpGet]
        [ActionName("OrderSubmit")]
        public Result_Model OrderSubmit()
        {
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            int m_CorpID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);// 1
            int m_WeixinId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.WeixinID);// 1
            int m_MemberID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);// 1

            try
            {
                y_Mall_Shopping _model = new y_Mall_Shopping();
                Hashtable ht = new Hashtable();
                ht["status"] = 0;
                ht["msg"] = "提交订单失败";
                if (m_MemberID == 0)
                {
                    ht["status"] = 0;
                    ht["msg"] = "请先登录，才允许提交订单！";
                    return new Result_Model((int)ht["status"], (string)ht["msg"], ht);
                }
                long li_FWeixinID = m_WeixinId;
                _model.FPrvID = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_Pid"]) ? 0 : Convert.ToInt32(HttpContext.Current.Request["J_Pid"]);
                _model.FCityID = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_Cid"]) ? 0 : Convert.ToInt32(HttpContext.Current.Request["J_Cid"]);
                _model.FAreaID = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_Arid"]) ? 0 : Convert.ToInt32(HttpContext.Current.Request["J_Arid"]);
                _model.FShippingID = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_CmpID"]) ? 0 : Convert.ToInt32(HttpContext.Current.Request["J_CmpID"]);
                _model.FPayID = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_PayID"]) ? 0 : Convert.ToInt32(HttpContext.Current.Request["J_PayID"]);
                _model.FCouponID = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_FCouponID"]) ? 0 : Convert.ToInt32(HttpContext.Current.Request["J_FCouponID"]);
                _model.FCouponMoney = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_FCouponMoney"]) ? 0 : Convert.ToDecimal(HttpContext.Current.Request["J_FCouponMoney"]);
                _model.FShippingAmt = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_ExpMoney"]) ? 0 : Convert.ToDecimal(HttpContext.Current.Request["J_ExpMoney"]);
                _model.FImportsFlag = string.IsNullOrWhiteSpace(HttpContext.Current.Request["J_FImportFlag"]) ? -1 : Convert.ToInt32(HttpContext.Current.Request["J_FImportFlag"]);
                _model.FBillFlag = HttpContext.Current.Request["J_FBillFlag"] == "on" ? 1 : 0;
                _model.FConsignee = HttpContext.Current.Request["J_FConsignee"];
                _model.FAddress = HttpContext.Current.Request["J_FPrCityArea"] + HttpContext.Current.Request["J_FAddress"];
                _model.FTelephone = HttpContext.Current.Request["J_FPhone"];
                _model.FMessage = HttpContext.Current.Request["J_FMessage"];
                _model.type = HttpContext.Current.Request["id"];
                _model.FGoodsID = CommonFun.ConvertToBigInt(HttpContext.Current.Request["GoodsID"]);
                _model.FCutIntegral = CommonFun.ConvertToDecimal(HttpContext.Current.Request["J_FCutIntegral"]);
                _model.FWeixinID = m_WeixinId;
                _model.FQty = 1;

                string goodsSeckillId = HttpContext.Current.Request["FSckillDetailID"];

                long li_CorpID = m_CorpID;

                if (_model.FPrvID <= 0 || _model.FCityID <= 0)
                {
                    ht["msg"] = "收货地址无效";
                    return new Result_Model((int)ht["status"], (string)ht["msg"], ht);
                }

                if (_model.FPayID <= 0)
                {
                    ht["msg"] = "请选择支付方式";
                    return new Result_Model((int)ht["status"], (string)ht["msg"], ht);
                }

                //获取用户 当前积分 和 商品所需积分
                ArrayList m_Info = DBHelper.Select("SELECT * FROM [dbo].[t_Member] where FItemID=@memberId", new List<SqlParameter>() { new SqlParameter("@memberId", m_MemberID) }.ToArray(), DBHelper.ConnMaster);
                if (m_Info.Count == 0)
                {
                    return new Result_Model(0, "会员不存在!");
                }

                // 用户积分
                int m_user_point = CommonFun.ConvertToInt((m_Info[0] as Hashtable)["FPoint"]);

                // 商品积分
                ArrayList good_Info = DBHelper.Select("SELECT * FROM [dbo].[t_Goods] where FItemID=@goodId", new List<SqlParameter>() { new SqlParameter("@goodId", _model.FGoodsID) }.ToArray(), DBHelper.ConnMaster);
                if (good_Info.Count == 0)
                {
                    return new Result_Model(0, "商品不存在!");
                }
                // 商品积分
                int m_good_point = CommonFun.ConvertToInt((good_Info[0] as Hashtable)["FPoint"]);

                if (m_good_point > m_user_point)
                {
                    return new Result_Model(0, "积分不足!");
                }


                long li_KInterID = 0;

                bool v = MemberCardService.GenOrder(_model, li_FWeixinID, li_CorpID, ref li_KInterID, m_good_point);
                if (v)
                {
                    return new Result_Model(1, "兑换成功!", new
                    {
                        J_KInterID = li_KInterID
                    });

                }

                return new Result_Model((int)ht["status"], (string)ht["msg"], ht);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.ToString());
                //Log.Debug(ex.Message, "提交订单出错：");
                return null;
            }
        }
        #endregion



        #region 获取订单数据
        /// <summary>
        /// 获取订单数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, HttpGet]
        [ActionName("GetOrderList")]
        public Result_Model GetOrderList()
        {
            Hashtable ht = new Hashtable();
            ht["status"] = 0;
            ht["msg"] = "载入订单数据失败！";
            ht["count"] = 0;

            string strJson = CommonFun.ConvertToString(HttpContext.Current.Request["strJson"]);
            //string json = CommonFun.ConvertToString(HttpContext.Current.Request["json"]);
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            int m_CorpID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);// 1
            int m_WeixinId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.WeixinID);// 1
            int m_MemberID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);// 1

            if (m_WeixinId > 0)
            {
                long li_CorpID = m_CorpID;
                T_OrderList _model = JsonConvert.DeserializeObject<T_OrderList>(strJson);
                int m_pageSize = 10;
                DataTable dt = MemberCardService.Get_Order_Payment(m_WeixinId, li_CorpID, _model.PageIndex, m_pageSize, _model);
                if (dt != null && dt.Rows.Count > 0)
                {
                    List<GoodsJson> orderlist = RegroupOrderList(li_CorpID, dt);
                    ht["status"] = 1;
                    ht["list"] = orderlist;
                    ht["msg"] = "数据加载完毕！";
                    ht["count"] = dt.Rows[0]["FRowCount"];
                }
                else if (dt.Rows.Count == 0 || dt == null)
                {
                    ht["status"] = 1;
                    ht["list"] = new List<GoodsJson>();
                    ht["msg"] = "数据加载完毕！";
                    ht["count"] = 0;
                }
                return new Result_Model((int)ht["status"], (string)ht["msg"], ht["list"], (int)ht["count"]);

            }
            else
            {
                ht["status"] = 0;
                ht["msg"] = "载入数据失败，请先登录！";
            }
            return new Result_Model((int)ht["status"], (string)ht["msg"], ht["list"], (int)ht["count"]);
        }
        #endregion

        /// <summary>
        /// 订单详情
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost, HttpGet]
        [ActionName("OrderDetail")]
        public Result_Model OrderDetail()
        {
            int status = 0;
            string sSystemAppID = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["mSystemAppID"]);
            int m_CorpID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);// 1
            int m_WeixinId = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.WeixinID);// 1
            int m_MemberID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);// 1
            if (m_WeixinId == 0)
            {
                return new Result_Model(status, "请先登录~");
            }

            Int64 orderId = CommonFun.ConvertToBigInt(HttpContext.Current.Request["orderId"]);
            DataTable dtOrder = ShopCartBill.GetOrderDetail(m_CorpID, orderId.ToString());
            List<GoodsJson> dtGoods = new List<GoodsJson>();
            if (dtOrder != null && dtOrder.Rows.Count > 0)
            {
                foreach (DataRow dra in ShopCartBill.Get_Mall_Detail(Convert.ToInt64(dtOrder.Rows[0]["KInterID"])).Rows)
                {
                    GoodsJson goods = new GoodsJson
                    {
                        id = dra["mFGoodID"].ToString()
                    };

                    if (string.IsNullOrEmpty(dra["FThumbImage"].ToString()))
                    {
                        //goods.img = "/images/NoImage.jpg";
                    }
                    else
                    {
                        goods.img = /*ConfigurationManager.AppSettings["ImgSaveUrl"] +*/ dra["FThumbImage"].ToString();
                    }

                    goods.title = dra["FName"].ToString();
                    goods.price = CommonFun.ConvertToDecimal(dra["mFActualPrice"]).ToString();
                    goods.qty = CommonFun.ConvertToBigInt(dra["mFQty"]).ToString();
                    goods.total = CommonFun.ConvertToBigInt(dra["mFRealAmount"]).ToString();
                    dtGoods.Add(goods);
                }
            }
            status = 1;
            return new Result_Model(status, "获取成功！", new Dictionary<string, object>
            {
                { "Order",dtOrder},
                { "Goods",dtGoods}
            });
        }



        /// <summary>
        /// 重新组合订单
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public List<GoodsJson> RegroupOrderList(long corpId, DataTable dt)
        {
            List<GoodsJson> orderlist = new List<GoodsJson>();
            foreach (DataRow dr in dt.Rows)
            {
                GoodsJson _pay = new GoodsJson();
                _pay.data = new List<GoodsJson>();
                _pay.entryid = dr["MInterID"].ToString();
                _pay.number = dr["FBillNo"].ToString();
                _pay.payname = dr["PayName"].ToString();
                _pay.piece = dr["FPiece"].ToString();
                _pay.payid = dr["FPayID"].ToString();
                _pay.paytype = dr["FPayType"].ToString();
                _pay.url = string.Format("/Order/OrderPayOauth/{0}", dr["MInterID"]);
                _pay.total = CommonFun.ConvertToDecimal(dr["FPayRealAmount"]).ToString();
                _pay.StateId = dr["FStateID"].ToString();
                _pay.StateName = dr["FStateName"].ToString();
                _pay.rowId = dr["FRowId"].ToString();
                _pay.RowCount = dr["FRowCount"].ToString();
                decimal totalPrice = 0;
                foreach (DataRow dra in ShopCartBill.Get_Mall_Detail(Convert.ToInt64(dr["MInterID"].ToString())).Rows)
                {
                    GoodsJson _order = new GoodsJson();
                    _order.href = string.Format("/OrderDetail/{0}/{1}.html", corpId, dr["MInterID"]);
                    if (string.IsNullOrEmpty(dra["FThumbImage"].ToString()))
                    {
                        //_order.img = "/images/NoImage.jpg";
                    }
                    else
                    {
                        _order.img = ConfigurationManager.AppSettings["ImgSaveUrl"] + dra["FThumbImage"];
                    }

                    _order.title = dra["FName"].ToString();
                    _order.price = CommonFun.ConvertToDecimal(dra["mFActualPrice"].ToString()).ToString();
                    _order.qty = CommonFun.ConvertToDecimal(dra["mFQty"].ToString()).ToString();
                    _order.total = CommonFun.ConvertToDecimal(dra["mFRealAmount"].ToString()).ToString();
                    totalPrice += CommonFun.ConvertToDecimal(dra["mFQty"]);

                    _pay.data.Add(_order);
                }
                _pay.qty = totalPrice.ToString();
                orderlist.Add(_pay);
            }
            return orderlist;
        }


        /// <summary>
        /// 1.64、获取微信支付信息
        /// </summary>
        [HttpPost]
        [ActionName("SetRenewalsPay")]
        public Result_Model SetRenewalsPay()
        {
            string msg = "";
            string shop_appid = CommonFun.ConvertToString(HttpContext.Current.Request.Headers["shop_appid"]);

            string openid = CommonFun.ConvertToString(HttpContext.Current.Request["openid"]);
            decimal total_fee = CommonFun.ConvertToDecimal(HttpContext.Current.Request["total_fee"]);
            int years = CommonFun.ConvertToInt(HttpContext.Current.Request["years"]);

            if (years == 0) years = 1;
            ArrayList rows = JsonConvert.DeserializeObject<ArrayList>(CommonFun.ConvertToString(HttpContext.Current.Request["detaileds"]));

            int shop_id = (int)SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);
            int user_id = (int)SystemInfo.GetSystemAppID(shop_appid, SystemAppID.UserID);

            int type = 0;//0是充值续费，2是短信充值
            Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(rows[0]));

            //生成支付订单
            string out_trade_no = MallCommon.SaveRenewalsOrder(shop_id, user_id, total_fee, years, ref msg, type, shop_appid, dic);
            if (out_trade_no == "") return new Result_Model(2, !string.IsNullOrEmpty(msg) ? msg : "生成订单失败");

            //开始调用支付
            Dictionary<string, object> result = new Dictionary<string, object>();
            // 原生支付
            bool ret = SxfPayCommon.GetCreateOrderPay(shop_id, openid, total_fee, out_trade_no, ref msg, out result);
            if (!ret) return new Result_Model(2, !string.IsNullOrEmpty(msg) ? msg : "获取失败");

            //查询支付结果
            MemberCardService.SetRepeatQueryPay(rows, out_trade_no, shop_id, years, type, shop_appid);
            return new Result_Model(1, "获取成功", result);
        }


    }
}